package com.huiyou.adminapi.controller;

import com.huiyou.adminapi.common.model.Product;
import com.huiyou.adminapi.service.ProductService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/product")
public class ProductController extends AbstractController {


    private ProductService productService;

    @Autowired
    public ProductController(ProductService productService) {
        this.productService = productService;
    }

    @GetMapping
    public Page<Product> findAll(String name, @PageableDefault Pageable pageable) {
        return productService.findAll(name, pageable);
    }

    @GetMapping("/{id}")
    public Product findById(@PathVariable("id") String id) {
        return this.productService.findById(id);
    }

    @PostMapping
    public void save(@RequestBody Product product) {
        this.productService.save(product);
    }

    @PutMapping("/{id}")
    public void update(@PathVariable("id") String id, @RequestBody Product product) {
        super.idCheckFound(this.productService.findById(id));
        this.productService.save(product);
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") String id) {
        this.productService.deleteById(id);
    }

}
